package com.mjk.common.web.getway.restful.prototal.ws.soap.utils;


import com.mjk.common.base.constns.BeeCommonConstns;
import com.mjk.common.tools.springextend.BeeSpringBean;
import com.mjk.common.web.getway.restful.prototal.ws.soap.proxy.BeeSoapClassLoader;
import com.mjk.common.web.getway.restful.prototal.ws.soap.proxy.BeeSoapInvcationHandler;
import com.mjk.common.web.getway.restful.prototal.ws.soap.proxy.BeeSoapProxy;
import groovy.lang.GroovyClassLoader;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;

import java.lang.reflect.InvocationHandler;

public class SoapUtils {
	/**
	 * webservice 接口发布
     */
	public static void publish(Class<?> clazz,String path,GroovyClassLoader groovyClassLoader) {
        if (!path.startsWith(BeeCommonConstns.BACKS_LASH)) {
            path = BeeCommonConstns.BACKS_LASH + path;
		}	
		InvocationHandler invcation = BeeSpringBean.getBean(BeeSoapInvcationHandler.class);
		Object proxy = BeeSoapProxy.newProxyInstance(new BeeSoapClassLoader(), new Class[] { clazz }, invcation,groovyClassLoader);
        //是否是重启
        boolean isRestart = doPublish(path, proxy);
        //重新发布
        if (!isRestart) {
            doPublish(path, proxy);
        }
    }

    public static boolean doPublish(String path, Object proxy) {
		SpringBus bus = BeeSpringBean.getBean(SpringBus.class);
        EndpointImpl endpoint = new EndpointImpl(bus, proxy);
        try {
			endpoint.publish(path);
            return true;
        } catch (Exception e) {
            endpoint.stop();
            return false;
		}
	}
}
